﻿using HalconDotNet;
using NDK.Module.BLL;
using NDK.Module.Model;
using NDK.Module.StationLogic;
using NDK.Motion.BLL;
using NDK.Motion.MachineManager;
using NDK.Motion.Sys;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VisionPlatform;

namespace NDK.Frm
{

    public partial class Frm_Setting : Form
    {
        #region 成员变量; 窗体、控件、DataGridView数据初始化，字段属性定义

        private static log4net.ILog m_Logger;
        private Dlg_FloatAndIntParamsSetting m_ParamsSettingDialog;
        private Dlg_BoolParamSetting m_BoolParamSettingDialog;
        private Dlg_StringParamSetting m_StringParamSettingDialog;
        #region 数据库相关属性
        //参数设置页
        private SQLiteDataAdapter m_ParamsFloatDataAdapter;
        private SQLiteDataAdapter m_ParamsIntDataAdapter;
        private SQLiteDataAdapter m_ParamsBoolDataAdapter;
        private SQLiteDataAdapter m_ParamsStringDataAdapter;
        private DataTable m_ParamsFloatDataTable;
        private DataTable m_ParamsIntDataTable;
        private DataTable m_ParamsBoolDataTable;
        private DataTable m_ParamsStringDataTable;
        //尺寸设置页
        private SQLiteDataAdapter m_SizeDataAdapter;
        private DataTable m_SizeDataTable;

        public DataTable SizeDataTable
        {
            get
            {
                return m_SizeDataTable;
            }
            set
            {
                m_SizeDataTable = value;
            }
        }
        public SQLiteDataAdapter SizeDataAdapter
        {
            get
            {
                return m_SizeDataAdapter;
            }
            set
            {
                m_SizeDataAdapter = value;
            }
        }
        public SQLiteDataAdapter ParamsFloatDataAdapter
        {
            get
            {
                return m_ParamsFloatDataAdapter;
            }
        }
        public SQLiteDataAdapter ParamsIntDataAdapter
        {
            get
            {
                return m_ParamsIntDataAdapter;
            }
        }
        public SQLiteDataAdapter ParamsBoolDataAdapter
        {
            get
            {
                return m_ParamsBoolDataAdapter;
            }
        }
        public SQLiteDataAdapter ParamsStringDataAdapter
        {
            get
            {
                return m_ParamsStringDataAdapter;
            }
        }
        public DataTable ParamsFloatDataTable
        {
            get
            {
                return m_ParamsFloatDataTable;
            }
        }
        public DataTable ParamsIntDataTable
        {
            get
            {
                return m_ParamsIntDataTable;
            }
        }
        public DataTable ParamsBoolDataTable
        {
            get
            {
                return m_ParamsBoolDataTable;
            }
        }
        public DataTable ParamsStringDataTable
        {
            get
            {
                return m_ParamsStringDataTable;
            }
        }
        #endregion

        private Frm_Setting()
        {
            InitializeComponent();
            //按屏幕分辨率布局窗体
            FrmLayout();
            //绑定数据源到DataGridview
            DgvBindSource();
            //默认第一个工程
            //Common.ProjectName = cb_Project.Items[0].ToString();
            Common.CheckTimeRefreshAction += Common_CheckTimeRefreshAction;
        }

        private void Common_CheckTimeRefreshAction(string obj)
        {
            foreach (DataRow item in ParamsStringDataTable.Rows)
            {
                if (nameof(Common.上次点检时间) == item[1].ToString())
                {
                    item[2] = obj;
                }
            }
            ParamsStringDataAdapter.Update(ParamsStringDataTable);
        }

        /// <summary>
        /// 窗体、控件布局，适应不同分辨率
        /// </summary>
        private void FrmLayout()
        {
            //参数设置页
            StyleUtils.SetSettingPageDGVStyle(dgv_Float);
            StyleUtils.SetSettingPageDGVStyle(dgv_Bool);
            StyleUtils.SetSettingPageDGVStyle(dgv_Int);
            StyleUtils.SetSettingPageDGVStyle(dgv_String);
        }

        /// <summary>
        /// 窗体对象实例，单例模式,保证整个工程只有一个实例
        /// </summary>
        private static Frm_Setting _instance;
        private static readonly object singletonLock = new object();
        public static Frm_Setting Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new Frm_Setting();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion 成员变量; 窗体、控件、DataGridView数据初始化，字段属性定义

        #region 解决闪烁问题
        /// <summary>
        /// 解决闪烁问题
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        #endregion

        #region 界面加载
        private void SettingForm_Load(object sender, EventArgs e)
        {
            m_Logger = log4net.LogManager.GetLogger(this.GetType());

            if (Common.Authority == "OP")
            {
                tab_SizeConfig.Visible = false;

                dgv_Float.Visible = false;
                dgv_Int.Visible = false;
            }
            else if (Common.Authority == "EN" || Common.Authority == "superadmin" || Common.Authority == "Apple" || Common.Authority == "CMT")
            {

            }
        }
        #endregion

        #region 参数设置页
        //参数更新
        private void btn_UpdateRuningParams_Click(object sender, EventArgs e)
        {
            PublicMethod.UpdateRuningData();
        }

        #region 事件：参数设置页添加、更新和删除的点击
        private void cms_ParamsFloat_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog = null;
            if (e.ClickedItem == toolStripMenuItem_Float_New)
            {
                #region 添加
                m_ParamsSettingDialog = new Dlg_FloatAndIntParamsSetting();
                m_ParamsSettingDialog.DgvName = this.dgv_Float.Name;
                m_ParamsSettingDialog.IsEditMode = false;
                if (m_ParamsSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_Float.CurrentCell = null;
                        m_ParamsFloatDataAdapter.Update(m_ParamsFloatDataTable);
                        RefreshDGV(dgv_Float, out m_ParamsFloatDataTable, m_ParamsFloatDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("添加浮点参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                        string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Float, 0);
                        confirmDialog = new Dlg_Comfirm("提示框", "添加浮点参数：" + cellValue + "失败！");
                        confirmDialog.ShowDialog(this);
                    }
                }
                #endregion
            }
            else if (e.ClickedItem == toolStripMenuItem_Float_Update)
            {
                #region 刷新
                RefreshDGV(dgv_Float, out m_ParamsFloatDataTable, m_ParamsFloatDataAdapter);
                #endregion
            }
            else if (e.ClickedItem == toolStripMenuItem_Float_Delete && !dgv_Float.CurrentRow.IsNewRow)
            {
                #region 删除
                //弹出删除确认框
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Float, 0);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除浮点参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    //删除SelectedRows
                    foreach (DataGridViewRow dataGridViewRow in dgv_Float.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                        {
                            dgv_Float.Rows.Remove(dataGridViewRow);
                        }
                    }
                    //更新到数据源
                    try
                    {
                        dgv_Float.CurrentCell = null;
                        m_ParamsFloatDataAdapter.Update(m_ParamsFloatDataTable);
                        RefreshDGV(dgv_Float, out m_ParamsFloatDataTable, m_ParamsFloatDataAdapter);
                    }
                    catch (Exception se)
                    {
                        m_Logger.Error("删除失败！" + se.Message);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                    }
                }
                #endregion
            }

        }
        private void cms_ParamsInt_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog = null;
            if (e.ClickedItem == toolStripMenuItem_Int_New)
            {
                m_ParamsSettingDialog = new Dlg_FloatAndIntParamsSetting();
                m_ParamsSettingDialog.DgvName = this.dgv_Int.Name;
                m_ParamsSettingDialog.IsEditMode = false;
                if (m_ParamsSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_Int.CurrentCell = null;
                        m_ParamsIntDataAdapter.Update(m_ParamsIntDataTable);
                        RefreshDGV(dgv_Int, out m_ParamsIntDataTable, m_ParamsIntDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("添加整型参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                        string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Int, 0);
                        confirmDialog = new Dlg_Comfirm("提示框", "添加整型参数：" + cellValue + "失败！");
                        confirmDialog.ShowDialog(this);
                    }
                }
            }
            else if (e.ClickedItem == toolStripMenuItem_Int_Update)
            {
                RefreshDGV(dgv_Int, out m_ParamsIntDataTable, m_ParamsIntDataAdapter);
            }
            else if (e.ClickedItem == toolStripMenuItem_Int_Delete && !dgv_Int.CurrentRow.IsNewRow)
            {
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Int, 0);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除整型参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (DataGridViewRow dataGridViewRow in dgv_Int.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                        {
                            dgv_Int.Rows.Remove(dataGridViewRow);
                        }
                    }
                    try
                    {
                        dgv_Int.CurrentCell = null;
                        m_ParamsIntDataAdapter.Update(m_ParamsIntDataTable);
                        RefreshDGV(dgv_Int, out m_ParamsIntDataTable, m_ParamsIntDataAdapter);
                    }
                    catch (Exception se)
                    {
                        m_Logger.Error("删除失败！" + se.Message);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                    }
                }

            }
        }
        private void cms_ParamsBool_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog = null;
            if (e.ClickedItem == toolStripMenuItem_Bool_New)
            {
                m_BoolParamSettingDialog = new Dlg_BoolParamSetting();
                m_BoolParamSettingDialog.IsEditMode = false;
                if (m_BoolParamSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_Bool.CurrentCell = null;
                        m_ParamsBoolDataAdapter.Update(m_ParamsBoolDataTable);
                        RefreshDGV(dgv_Bool, out m_ParamsBoolDataTable, m_ParamsBoolDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("添加布尔参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                        string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Bool, 0);
                        confirmDialog = new Dlg_Comfirm("提示框", "添加布尔参数：" + cellValue + "失败！");
                        confirmDialog.ShowDialog(this);
                    }
                }
            }
            else if (e.ClickedItem == toolStripMenuItem_Bool_Update)
            {
                RefreshDGV(dgv_Bool, out m_ParamsBoolDataTable, m_ParamsBoolDataAdapter);
            }
            else if (e.ClickedItem == toolStripMenuItem_Bool_Delete && !dgv_Bool.CurrentRow.IsNewRow)
            {
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_Bool, 0);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除布尔参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (DataGridViewRow dataGridViewRow in dgv_Bool.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                        {
                            dgv_Bool.Rows.Remove(dataGridViewRow);
                        }
                    }

                    try
                    {
                        dgv_Bool.BeginInvoke(new Action(() =>
                        {
                            dgv_Bool.CurrentCell = null;
                        }));
                        m_ParamsBoolDataAdapter.Update(m_ParamsBoolDataTable);
                        RefreshDGV(dgv_Bool, out m_ParamsBoolDataTable, m_ParamsBoolDataAdapter);
                    }
                    catch (Exception se)
                    {
                        m_Logger.Error("删除失败！" + se.Message);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                    }
                }

            }
        }
        private void cms_ParasString_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog = null;
            if (e.ClickedItem == toolStripMenuItem_String_New)
            {
                m_StringParamSettingDialog = new Dlg_StringParamSetting();
                m_StringParamSettingDialog.IsEditMode = false;
                if (m_StringParamSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_String.CurrentCell = null;
                        m_ParamsStringDataAdapter.Update(m_ParamsStringDataTable);
                        RefreshDGV(dgv_String, out m_ParamsStringDataTable, m_ParamsStringDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("添加字符串参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                        string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_String, 0);
                        confirmDialog = new Dlg_Comfirm("提示框", "添加字符串参数：" + cellValue + "失败！");
                        confirmDialog.ShowDialog(this);
                    }
                }
            }
            else if (e.ClickedItem == toolStripMenuItem_String_Update)
            {
                RefreshDGV(dgv_String, out m_ParamsStringDataTable, m_ParamsStringDataAdapter);
            }
            else if (e.ClickedItem == toolStripMenuItem_String_Delete && !dgv_String.CurrentRow.IsNewRow)
            {
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_String, 0);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除字符串参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (DataGridViewRow dataGridViewRow in dgv_String.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                            dgv_String.Rows.Remove(dataGridViewRow);
                    }
                }
                try
                {
                    dgv_String.CurrentCell = null;
                    m_ParamsStringDataAdapter.Update(m_ParamsStringDataTable);
                    RefreshDGV(dgv_String, out m_ParamsStringDataTable, m_ParamsStringDataAdapter);
                }
                catch (Exception se)
                {
                    m_Logger.Error("删除失败！" + se.Message);
                    //Utils.SQLiteUtils.CloseDB(m_Conn);
                }
            }
        }

        /// <summary>
        /// 将数据库中的值刷新到datagridview
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <param name="dt">DataTable</param>
        /// <param name="sda">SQLiteDataAdapter</param>
        /// <returns></returns>
        private bool RefreshDGV(DataGridView dgv, out DataTable dt, SQLiteDataAdapter sda)
        {
            dt = new DataTable();
            sda.Fill(dt);
            dgv.BeginInvoke(new Action<DataTable>((DataTable dt1) =>
            {
                dgv.DataSource = dt1;
            }), new object[] { dt });
            return true;
        }
        #endregion

        #region 事件：cell进入编辑状态时, 弹出编辑对话框
        //dgv_Float, cell进入编辑状态时, 弹出编辑对话框
        private void dgv_Float_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (!dgv_Float.CurrentRow.IsNewRow)
            {
                m_ParamsSettingDialog = new Dlg_FloatAndIntParamsSetting();
                m_ParamsSettingDialog.IsEditMode = true;
                m_ParamsSettingDialog.DgvName = this.dgv_Float.Name;
                m_ParamsSettingDialog.EditIndex = e.RowIndex;
                if (m_ParamsSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    //try
                    //{
                    //    //更新dgv_Float
                    //    dgv_Float.CurrentCell = null;
                    //    m_ParamsFloatDataAdapter.Update(m_ParamsFloatDataTable);
                    //    m_ParamsFloatDataTable = new DataTable();
                    //    m_ParamsFloatDataAdapter.Fill(m_ParamsFloatDataTable);
                    //    dgv_Float.DataSource = m_ParamsFloatDataTable;
                    //}
                    //catch (Exception ex)
                    //{
                    //    m_Logger.Error("编辑该行数据失败！" + ex.StackTrace);
                    //}
                }
                //else
                //{
                //    //定位焦点到首行首列
                //    dgv_Float.CurrentCell = dgv_Float[0, 0];
                //}
                e.Cancel = true;
            }
        }
        //dgv_Int,cell进入编辑状态时, 弹出编辑对话框
        private void dgv_Int_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (!dgv_Int.CurrentRow.IsNewRow)
            {
                m_ParamsSettingDialog = new Dlg_FloatAndIntParamsSetting();
                m_ParamsSettingDialog.IsEditMode = true;
                m_ParamsSettingDialog.DgvName = this.dgv_Int.Name;
                m_ParamsSettingDialog.EditIndex = e.RowIndex;
                if (m_ParamsSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    //try
                    //{
                    //    dgv_Int.CurrentCell = null;
                    //    m_ParamsIntDataAdapter.Update(m_ParamsIntDataTable);
                    //    RefreshDGV(dgv_Int, out m_ParamsIntDataTable, m_ParamsIntDataAdapter);
                    //}
                    //catch (Exception ex)
                    //{
                    //    m_Logger.Error("编辑整型参数失败！" + ex.StackTrace);
                    //}
                }
                //else
                //{
                //    dgv_Int.CurrentCell = dgv_Int[0, 0];
                //}
                e.Cancel = true;
            }
        }
        //dgv_Bool,cell进入编辑状态时, 弹出编辑对话框
        private void dgv_Bool_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (!dgv_Bool.CurrentRow.IsNewRow)
            {
                m_BoolParamSettingDialog = new Dlg_BoolParamSetting();
                m_BoolParamSettingDialog.EditIndex = e.RowIndex;
                m_BoolParamSettingDialog.IsEditMode = true;
                if (m_BoolParamSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    //try
                    //{
                    //    //dgv_Bool.CurrentCell = null;
                    //    //m_ParamsBoolDataAdapter.Update(m_ParamsBoolDataTable);
                    //    //RefreshDGV(dgv_Bool, out m_ParamsBoolDataTable, m_ParamsBoolDataAdapter);

                    //}
                    //catch (Exception ex)
                    //{
                    //    m_Logger.Error("编辑布尔参数失败！" + ex.StackTrace);
                    //}
                }
                //else
                //{
                //    dgv_Bool.CurrentCell = dgv_Bool[0, 0];
                //}

                e.Cancel = true;

            }
        }
        //dgv_String,cell进入编辑状态时, 弹出编辑对话框
        private void dgv_String_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (!dgv_String.CurrentRow.IsNewRow)
            {
                m_StringParamSettingDialog = new Dlg_StringParamSetting();
                m_StringParamSettingDialog.EditIndex = e.RowIndex;
                m_StringParamSettingDialog.IsEditMode = true;
                if (m_StringParamSettingDialog.ShowDialog(this) == DialogResult.OK)
                {
                    try
                    {
                        dgv_String.CurrentCell = null;
                        m_ParamsStringDataAdapter.Update(m_ParamsStringDataTable);
                        RefreshDGV(dgv_String, out m_ParamsStringDataTable, m_ParamsStringDataAdapter);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Error("编辑字符串参数失败！" + ex.StackTrace);
                        //Utils.SQLiteUtils.CloseDB(m_Conn);
                    }
                }
                //else
                //{
                //    dgv_String.CurrentCell = dgv_String[0, 0];
                //}
                e.Cancel = true;
                //dgv_String.EndEdit();

            }
        }
        #endregion

        #endregion 参数设置页

        #region 数据设置页
        //尺寸配置：添加、刷新、删除
        private void cms_SizeConfig_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            Dlg_Comfirm confirmDialog;
            if (e.ClickedItem == tsmi_SaveSize)
            {
                #region 保存
                try
                {
                    dgv_SizeConfig.CurrentCell = null;
                    m_SizeDataAdapter.Update(m_SizeDataTable);
                    RefreshDGV(dgv_SizeConfig, out m_SizeDataTable, m_SizeDataAdapter);
                }
                catch (Exception ex)
                {
                    m_Logger.Error("添加尺寸参数失败！" + ex.StackTrace);
                    //Utils.SQLiteUtils.CloseDB(m_Conn);
                    string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_SizeConfig, 0);
                    confirmDialog = new Dlg_Comfirm("提示框", "添加尺寸参数：" + cellValue + "失败！");
                    confirmDialog.ShowDialog(this);
                }
                #endregion
            }
            if (e.ClickedItem == tsmi_UpdateSize)
            {
                RefreshDGV(dgv_SizeConfig, out m_SizeDataTable, m_SizeDataAdapter);
                dgv_SizeConfig.Columns["K"].Visible = false;
                dgv_SizeConfig.Columns["B"].Visible = false;
            }
            if (e.ClickedItem == tsmi_DeleteSize)
            {
                #region 删除
                string cellValue = DataGridViewUtils.GetDataGridViewCurrentRowCellValue(dgv_SizeConfig, 1);
                confirmDialog = new Dlg_Comfirm("确认框", "确认删除尺寸输入参数：" + cellValue + "吗？");
                if (confirmDialog.ShowDialog(this) == DialogResult.OK)
                {
                    foreach (DataGridViewRow dataGridViewRow in dgv_SizeConfig.SelectedRows)
                    {
                        if (!dataGridViewRow.IsNewRow)
                        {
                            dgv_SizeConfig.Rows.Remove(dataGridViewRow);
                        }
                    }
                    try
                    {
                        dgv_SizeConfig.CurrentCell = null;
                        m_SizeDataAdapter.Update(m_SizeDataTable);
                        RefreshDGV(dgv_SizeConfig, out m_SizeDataTable, m_SizeDataAdapter);
                    }
                    catch (Exception se)
                    {
                        m_Logger.Error("删除失败！" + se.Message);
                        //SQLiteUtils.CloseDB(m_Conn);
                    }
                }
                #endregion
            }
            if (e.ClickedItem == tsmi_LoadSize)
            {
                LoadSize(m_SizeDataTable);
            }

            void LoadSize(DataTable sizeDataTable)
            {
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.Title = "请选择文件";
                fileDialog.Filter = "csv文件|*.csv";
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    //得到绝对路径
                    string file = fileDialog.FileName;
                    try
                    {
                        using (StreamReader sr = new StreamReader(file, Encoding.Default))
                        {
                            string line = "";
                            int rowIndex = 0;
                            while ((line = sr.ReadLine()) != null)
                            {
                                line = line.Replace("\t", ",");
                                string[] sizes = line.Split(',');
                                {

                                    DataRow dr = sizeDataTable.NewRow();
                                    dr[1] = sizes[0];//元素名称
                                    dr[2] = sizes[1];//属性
                                    dr[3] = sizes[2];//理论值
                                    dr[4] = sizes[3];//上偏差
                                    dr[5] = sizes[4];//下偏差
                                    sizeDataTable.Rows.Add(dr);
                                }
                            }
                        }
                        m_SizeDataAdapter.Update(m_SizeDataTable);
                        RefreshDGV(dgv_SizeConfig, out m_SizeDataTable, m_SizeDataAdapter);
                    }
                    catch (FileLoadException ex)
                    {
                        MessageBox.Show("文件加载失败，检查是否文件已经被其他应用打开\r\n" + file);
                    }
                }
            }
        }
        #endregion 数据设置页

        #region 其他
        /// <summary>
        /// 绑定数据源到DataGridview
        /// </summary>
        public void DgvBindSource()
        {
            //参数设置页
            m_ParamsFloatDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_Float, out m_ParamsFloatDataAdapter, Common.DatabaseName, "FloatParams");
            m_ParamsIntDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_Int, out m_ParamsIntDataAdapter, Common.DatabaseName, "IntParams");
            m_ParamsBoolDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_Bool, out m_ParamsBoolDataAdapter, Common.DatabaseName, "BoolParams");
            m_ParamsStringDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_String, out m_ParamsStringDataAdapter, Common.DatabaseName, "StringParams");
            m_SizeDataTable = SQLiteUtils.DataSourceBindToDataGridView(dgv_SizeConfig, out m_SizeDataAdapter, Common.DatabaseName, "MeasureSize", new string[1] { "project" }, new string[1] { Common.CurProType });
        }
        #endregion


        #region 测试页面
        //结果强制操作
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            Common.isForceOK = CB_ReOK.Checked;
            Common.isForceNG = CB_ReNG.Checked;
            Common.isForceORT = CB_ReORT.Checked;
            Common.isForceNA = CB_ReNA.Checked;
        }

        //PLC测试
        private void btn_PLCTest_Click(object sender, EventArgs e)
        {
            Frm_PLCCommTest.Instance.ShowDialog();
        }

        //相机连接
        private void button11_Click(object sender, EventArgs e)
        {
            if (Btn_断开相机.Text == "断开所有相机")
            {
                if (Common.HikVisionList != null)
                {
                    foreach (var item in Common.HikVisionList)
                    {
                        item.DisConnect();
                    }
                    Btn_断开相机.Text = "连接所有相机";
                }
            }
            else
            {
                if (Common.HikVisionList != null)
                {
                    foreach (var item in Common.HikVisionList)
                    {
                        item.Connect();
                    }
                    Btn_断开相机.Text = "断开所有相机";
                }
            }
        }
        #endregion


        #region 工站调试

        private void btn_ReadPPG_Click(object sender, EventArgs e)
        {
            btn_ReadPPG.Enabled = false;
            Task.Run(() =>
            {
                List<double> list = new List<double>();
                for (int i = 0; i < 8; i++)
                {
                    var rtn = Machine.PPG.ReadCH();
                    if (rtn.Code == Module.Model.Quebec.KeyencePPG.RtnCode.OK)
                        list.Add(rtn.Value);
                }

                if (list.Count >= 3)
                {
                    list.Remove(list.Max());
                    list.Remove(list.Min());

                    double Value = Math.Abs(Math.Round(list.Average(), 4) + Common.DP_PPG补偿1);
                    Invoke(new Action(() =>
                    {
                        txt_PPG.Text = Value.ToString();
                    }));
                }
            });

            btn_ReadPPG.Enabled = true;

        }

        private void btn_ZeroPPG_Click(object sender, EventArgs e)
        {
            Machine.PPG.SetZero();
        }

        private void btn_PPGWork_Click(object sender, EventArgs e)
        {
            MotionControl.AxesMove(Machine.pos_下压位_PPG下压工位);
        }

        private void btn_PPGHome_Click(object sender, EventArgs e)
        {
            //Machine.cy_PPG气缸.Home();
            MotionControl.AxesMove(Machine.pos_安全位_PPG下压工位);
        }

        private void btn_ReadPPGDecimal_Click(object sender, EventArgs e)
        {
            var rtn = Machine.PPG.ReadDecimal();
            if (rtn.Code == Module.Model.Quebec.KeyencePPG.RtnCode.OK)
            {
                Invoke(new Action(() =>
                {
                    txt_PPG.Text = rtn.Value.ToString();
                }));
            }

        }

        private void btn_SendCmd_Click(object sender, EventArgs e)
        {
            string cmd = txt_PPG.Text.Trim();
            var rtn = Machine.PPG.SendCmd(cmd);
            Invoke(new Action(() =>
            {
                txt_PPG.Text = rtn.Value.ToString();
            }));
        }



        private void button20_Click(object sender, EventArgs e)
        {
            var rtn = Machine.PPG.ReadDecimal("02");
            if (rtn.Code == Module.Model.Quebec.KeyencePPG.RtnCode.OK)
            {
                Invoke(new Action(() =>
                {
                    textBox2.Text = rtn.Value.ToString();
                }));
            }
        }

        private void button19_Click(object sender, EventArgs e)
        {
            string cmd = textBox2.Text.Trim();
            var rtn = Machine.PPG.SendCmd(cmd);
            Invoke(new Action(() =>
            {
                textBox2.Text = rtn.Value.ToString();
            }));
        }

        private void button24_Click(object sender, EventArgs e)
        {
            (sender as Button).Enabled = false;
            Task.Run(() =>
            {
                List<double> list = new List<double>();
                for (int i = 0; i < 8; i++)
                {
                    var rtn = Machine.PPG.ReadCH("02");
                    if (rtn.Code == Module.Model.Quebec.KeyencePPG.RtnCode.OK)
                        list.Add(rtn.Value);
                }

                if (list.Count >= 3)
                {
                    list.Remove(list.Max());
                    list.Remove(list.Min());

                    double Value = Math.Abs(Math.Round(list.Average(), 4) + Common.DP_PPG补偿2);
                    Invoke(new Action(() =>
                    {
                        textBox2.Text = Value.ToString();
                    }));
                }
            });

            (sender as Button).Enabled = true;
        }

        private async void Btn_相机拍照测试_Click(object sender, EventArgs e)
        {
            Btn_相机拍照测试.Enabled = false;
            await Task.Run(() =>
            {
                if (RB_定位相机.Checked)
                {
                    Common.HikVisionList[3].Snap();
                    HImage hImage = Common.HikVisionList[3].HalconImage(3000);
                    HalconDotNet.HOperatorSet.WriteImage(hImage, "bmp", 0, $"D:\\Data\\output\\Test\\定位相机");
                }
                else if (RB_工位2相机.Checked)
                {
                    Common.HikVisionList[2].Snap();
                    HImage hImage = Common.HikVisionList[2].HalconImage(3000);
                    HalconDotNet.HOperatorSet.WriteImage(hImage, "bmp", 0, $"D:\\Data\\output\\Test\\2");
                }
                else if (RB_工位3相机.Checked)
                {
                    Common.HikVisionList[1].Snap();
                    HImage hImage = Common.HikVisionList[1].HalconImage(3000);
                    HalconDotNet.HOperatorSet.WriteImage(hImage, "bmp", 0, $"D:\\Data\\output\\Test\\3");
                }
                else if (RB_工位4相机.Checked)
                {
                    Common.HikVisionList[0].Snap();
                    HImage hImage = Common.HikVisionList[0].HalconImage(3000);
                    HalconDotNet.HOperatorSet.WriteImage(hImage, "bmp", 0, $"D:\\Data\\output\\Test\\4");
                }

            });
            Btn_相机拍照测试.Enabled = true;
        }

        private async void Btn_九点标定_Click(object sender, EventArgs e)
        {
            (sender as Button).Enabled = false;
            await Task.Run(async () =>
            {
                int count = 0;
                while (true)
                {
                    Machine.imageLights_上料定位光源.Open();
                    if (Common.PLCAdr.DicInPutValue[Module.StationLogic.PLCInPut.上料拍照])
                    {
                        count++;
                        Common.HikVisionList[3].Snap();      //TOM修改
                        HImage hImage = Common.HikVisionList[3].HalconImage();
                        if (hImage == null)
                        {
                            break;
                        }
                        Common.OmronPLC.Write(Common.PLCAdr.DicOutPutBool[PLCOutPutBool.定位OK], true);
                        VisionProcess(hImage);
                        HOperatorSet.WriteImage(hImage, "bmp", 0, $"D:\\Data\\output\\Test\\九点标定\\{count}");
                        while (Common.PLCAdr.DicInPutValue[Module.StationLogic.PLCInPut.上料拍照])
                        {
                            await Task.Delay(100);
                        }
                        Common.OmronPLC.Write(Common.PLCAdr.DicOutPutBool[PLCOutPutBool.定位OK], false);
                    }
                    if (count == 14)
                        break;
                }
            });
            (sender as Button).Enabled = true;

            bool VisionProcess(HImage image)
            {
                try
                {
                    VisionManager.Engine VisionEngine = new VisionManager.Engine("九点标定");
                    VisionEngine.SetInputImage("Image", image);
                    VisionEngine.ActionFun();
                }
                catch (Exception ex)
                {
                    return false;
                }
                return true;
            }
        }

        private void Btn_断开激光_Click(object sender, EventArgs e)
        {
            if (Btn_断开激光.Text == "断开深视激光")
            {
                Common.SSZN_上激光.DisConnect();
                Common.SSZN_侧激光.DisConnect();
                Common.SSZN_下激光.DisConnect();
                Btn_断开相机.Text = "连接深视激光";
                MessageBox.Show("深视激光已断开");
            }
            else
            {
                if (Btn_断开激光.Text == "连接深视激光")
                {
                    Common.SSZN_上激光.Connect(Common.SP_工位3_深视上激光IP);
                    Common.SSZN_侧激光.Connect(Common.SP_工位7_深视侧激光IP);
                    Common.SSZN_下激光.Connect(Common.SP_深视下激光IP);
                    Btn_断开相机.Text = "断开深视激光";
                    MessageBox.Show("深视激光已连接");
                }
            }
        }

        public string 存图位置 = @"D:\Data\image\工站激光存图";
        private async void Btn_三激光取图_Click(object sender, EventArgs e)
        {
            Btn_三激光取图.Enabled = false;
            await Task.Run(async () =>
             {
                 try
                 {
                     if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Ready)
                     {
                         if (MotionControl.AxesMove(Machine.pos_激光扫描起始位_转盘工位三))
                         {
                             Common.SSZN_上激光.Start();
                         }
                         MotionControl.AxesMove(Machine.pos_激光扫描终点位_转盘工位三);
                         Common.SSZN_上激光.Stop();
                         var image = Common.SSZN_上激光.HeightImage();
                         await Task.Delay(500);
                         MotionControl.AxesMove(Machine.pos_激光扫描起始位_转盘工位三);
                         if (image != null)
                         {
                             PublicMethod.SaveImageLaser(image, 存图位置, "上激光" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second + "_" + DateTime.Now.Millisecond);
                         }
                     }
                     else
                     {
                         MessageBox.Show("请先初始化设备再测试激光");
                     }
                 }
                 catch { Exception ex; }
             });

            Btn_三激光取图.Enabled = true;
        }

        private async void Btn_七激光取图_Click(object sender, EventArgs e)
        {
            Btn_七激光取图.Enabled = false;
            await Task.Run(async () =>
            {
                try
                {
                    if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Ready)
                    {
                        if (MotionControl.AxesMove(Machine.pos_激光扫描起始位_转盘工位七))
                        {
                            Common.SSZN_侧激光.Start();
                        }
                        MotionControl.AxesMove(Machine.pos_激光扫描终点位_转盘工位七);
                        var image1 = Common.SSZN_侧激光.HeightImage();
                        Common.SSZN_侧激光.Stop();
                        await Task.Delay(500);
                        MotionControl.AxesMove(Machine.pos_激光扫描起始位_转盘工位七);
                        if (image1 != null)
                        {
                            PublicMethod.SaveImageLaser(image1, 存图位置, "侧激光" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second);
                        }
                    }
                    else
                    {
                        MessageBox.Show("请先初始化设备再测试激光");
                    }
                }
                catch
                {
                    Exception ex;
                }
                Btn_七激光取图.Enabled = true;
            });
        }

        private async void Btn_下激光取图_Click(object sender, EventArgs e)
        {
            Btn_下激光取图.Enabled = false;
            await Task.Run(async () =>
            {
                try
                {
                    if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Ready)
                    {
                        if (MotionControl.AxesMove(Machine.pos_激光扫描起始位_下激光工位))
                        {
                            Common.SSZN_下激光.Start();
                        }
                        MotionControl.AxesMove(Machine.pos_激光扫描终点位_下激光工位);
                        var image1 = Common.SSZN_下激光.HeightImage();
                        MotionControl.AxesMove(Machine.pos_激光扫描起始位_下激光工位);
                        Common.SSZN_下激光.Stop();
                        await Task.Delay(500);
                        if (image1 != null)
                        {
                            PublicMethod.SaveImageLaser(image1, 存图位置, "下激光" + DateTime.Now.Hour + "_" + DateTime.Now.Minute + "_" + DateTime.Now.Second);
                        }
                    }
                    else
                    {
                        MessageBox.Show("请先初始化设备再测试激光");
                    }

                }
                catch { Exception ex; }
                Btn_下激光取图.Enabled = true;
            });

        }

        private async void Btn_五工站激光取图_Click(object sender, EventArgs e)
        {
            Btn_五工站激光取图.Enabled = false;
            await Task.Run(async () =>
            {
                try
                {
                    if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Ready)
                    {
                        if (MotionControl.AxesMove(Machine.pos_激光扫描起始位_转盘工位五))
                        {
                            Common.Lmi_短边前激光.Start();
                            //Common.Lmi_短边后激光.Connect(Common.SP_工位5_LMI短边后激光IP);
                            Common.Lmi_短边后激光.Start();
                        }
                        MotionControl.AxesMove(Machine.pos_激光扫描终点位_转盘工位五);

                        var image1 = Common.Lmi_短边前激光.HeightImage();
                        var image2 = Common.Lmi_短边后激光.HeightImage();
                        Common.Lmi_短边前激光.Stop();
                        Common.Lmi_短边后激光.Stop();
                        MotionControl.AxesMove(Machine.pos_激光扫描起始位_转盘工位五);
                        await Task.Delay(500);
                        if (image1 != null)
                        {
                            PublicMethod.SaveImageLaser(image1, 存图位置, "S1");
                        }
                        if (image2 != null)
                        {
                            PublicMethod.SaveImageLaser(image2, 存图位置, "S2");
                        }
                    }
                    else
                    {
                        MessageBox.Show("请先初始化设备再测试激光");
                    }

                }
                catch { Exception ex; }
                Btn_五工站激光取图.Enabled = true;
            });
        }

        private async void Btn_六工站激光取图_Click(object sender, EventArgs e)
        {
            Btn_六工站激光取图.Enabled = false;
            await Task.Run(async () =>
            {
                try
                {
                    if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Ready)
                    {
                        if (MotionControl.AxesMove(Machine.pos_激光扫描起始位_转盘工位六))
                        {
                            Common.Lmi_长边左激光.Start();
                            Common.Lmi_长边右激光.Start();
                        }
                        MotionControl.AxesMove(Machine.pos_激光扫描终点位_转盘工位六);
                        var image1 = Common.Lmi_长边左激光.HeightImage();
                        var image2 = Common.Lmi_长边右激光.HeightImage();
                        Common.Lmi_长边左激光.Stop();
                        Common.Lmi_长边右激光.Stop();
                        await Task.Delay(500);
                        MotionControl.AxesMove(Machine.pos_激光扫描安全位_转盘工位六);
                        if (image1 != null)
                        {
                            PublicMethod.SaveImageLaser(image1, 存图位置, "L2");
                        }
                        if (image2 != null)
                        {
                            PublicMethod.SaveImageLaser(image2, 存图位置, "L1");
                        }
                    }
                    else
                    {
                        MessageBox.Show("请先初始化设备再测试激光");
                    }

                }
                catch { Exception ex; }
                Btn_六工站激光取图.Enabled = true;
            });
        }

        private void Btn_MES设置_Click(object sender, EventArgs e)
        {
            Dlg_loginMes dlg_LoginMes = new Dlg_loginMes();
            dlg_LoginMes.ShowDialog();
        }

        private void Btn_ppgGrr_Click(object sender, EventArgs e)
        {
            Btn_ppgGrr.Enabled = false;
            try
            {
                Common.PPG循环次数 = int.Parse(textBox1.Text.Trim());
                Common.PPG循环启动 = true;
            }
            catch (Exception)
            {

            }
            Btn_ppgGrr.Enabled = true;
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            await Task.Run(async () =>
            {
                try
                {
                    if (MotionControl.AxesMove(Machine.pos_取料接近位_下料翻转工位))
                    {
                        if (MotionControl.AxesMove(Machine.pos_PPG下方位_PPG搬运工位))
                        {
                            MotionControl.AxesMove(Machine.pos_接料位_PPG搬运工位);
                        }
                        else if (MotionControl.AxesMove(Machine.pos_接料位_PPG搬运工位))
                        {
                            MotionControl.AxesMove(Machine.pos_PPG下方位_PPG搬运工位);
                        }
                    }

                }
                catch (Exception)
                {

                }
                button1.Enabled = true;

            });
        }
    }
    #endregion
}
